// toast-manager.js

class ToastManager {
    constructor() {
        this.toastQueue = [];
        this.isShowingToast = false;
        this.init();
    }

    init() {
        const toastHtml = `
      <div class="toast-container position-fixed top-0 start-50 translate-middle-x p-3" style="z-index: 1070;">
        <div id="liveToast" class="toast align-items-center text-white border-0" role="alert" aria-live="assertive" aria-atomic="true">
          <div class="d-flex">
            <div class="toast-body" id="toastMessage"></div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
          </div>
        </div>
      </div>
    `;

        $('body').append(toastHtml);
    }

    showToast(message, isSuccess = true) {
        this.toastQueue.push({message, isSuccess});
        if (!this.isShowingToast) {
            this.showNextToast();
        }
    }

    showNextToast() {
        if (this.toastQueue.length === 0) {
            this.isShowingToast = false;
            return;
        }

        this.isShowingToast = true;
        const {message, isSuccess} = this.toastQueue.shift();

        const $toastElement = $('#liveToast');
        const toast = new bootstrap.Toast($toastElement[0], {
            animation: true,
            autohide: true,
            delay: 1000
        });

        $('#toastMessage').text(message);

        $toastElement
            .removeClass('bg-success bg-danger')
            .addClass(isSuccess ? 'bg-success' : 'bg-danger');

        toast.show();

        $toastElement.one('hidden.bs.toast', () => {
            setTimeout(() => this.showNextToast(), 300);
        });
    }
}

$(() => {
    const toastManager = new ToastManager();
    window.showToast = (message, isSuccess) => toastManager.showToast(message, isSuccess);
});